﻿using System.Composition;
using System.Composition.Hosting;
using System.Reflection;
using torch.plugin;
using System.Collections.Generic;
using System.Composition;
using System.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Serilog;

namespace torch.plugin_manager;

public class PluginManager
{
    private readonly string _pluginDirectory;
    private CompositionHost? _container;

    [ImportMany] public IEnumerable<IPlugin> Plugins { get; set; } = Enumerable.Empty<IPlugin>();

    public PluginManager(string pluginDirectory)
    {
        _pluginDirectory = pluginDirectory;
    }

    /// <summary>
    /// 下载并加载插件
    /// </summary>
    /// <param name="url">插件下载地址</param>
    /// <param name="fileName">保存的文件名</param>
    /// <param name="progress">下载进度</param>
    // public async Task<IPlugin?> DownloadAndLoadPluginAsync(
    //     string url,
    //     string fileName,
    //     IProgress<double>? progress = null)
    // {
    //     // 下载插件
    //     var downloader = new PluginDownloader(_pluginDirectory);
    //     var filePath = await downloader.DownloadPluginAsync(url, fileName, progress);
    // }
    public IEnumerable<IPlugin> LoadPlugins()
    {
        // 获取插件目录下所有的DLL文件
        var pluginFiles = Directory.GetFiles(_pluginDirectory, "*.dll", SearchOption.TopDirectoryOnly);

        // 创建MEF2容器配置
        var configuration = new ContainerConfiguration();

        // 加载每个DLL并检查是否包含IPlugin实现
        foreach (var file in pluginFiles)
        {
            try
            {
                Log.Debug($"正在加载插件: {file}");
                // 加载程序集
                var assembly = Assembly.LoadFrom(file);

                // 检查程序集中是否有实现IPlugin的类型
                if (assembly.GetExportedTypes().Any(t => typeof(IPlugin).IsAssignableFrom(t) && !t.IsAbstract))
                {
                    // 将符合条件的程序集添加到容器配置
                    configuration.WithAssembly(assembly);
                    Log.Information($"已加载插件: {file}");
                }
            }
            catch (Exception ex)
            {
                // 处理加载错误（如不是.NET程序集、损坏的文件等）
                Log.Error(ex, $"加载插件 {file} 失败: {ex.Message}");
            }
        }

        // 创建容器并获取所有IPlugin实例
        using (var container = configuration.CreateContainer())
        {
            return container.GetExports<IPlugin>().ToList();
        }
    }

    /// <summary>
    /// 卸载所有插件
    /// </summary>
    public void UnloadAllPlugins()
    {
        foreach (var plugin in Plugins)
        {
            plugin.Dispose();
        }

        _container?.Dispose();
        _container = null;
    }
}